// pages/register/register.js
const api = require('../../utils/api.js')
const app = getApp()

Page({
    data: {
        nickname: '',
        phone: '',
        submitting: false,
        openid: '',
        canSubmit: false
    },

    onLoad() {
        // 获取openid
        this.setData({
            openid: app.globalData.openid
        })
    },

    // 输入姓名
    onNicknameInput(e) {
        this.setData({
            nickname: e.detail.value
        }, () => {
            this.checkCanSubmit()
        })
    },

    // 检查是否可以提交
    checkCanSubmit() {
        const canSubmit = this.data.nickname.trim() !== '' && this.data.phone !== ''
        this.setData({ canSubmit })
    },

    // 获取手机号
    getPhoneNumber(e) {
        console.log('获取手机号', e)

        if (e.detail.errMsg === 'getPhoneNumber:ok') {
            const { code } = e.detail

            wx.showLoading({ title: '获取中...' })

            // 发送code到后端解密手机号
            api.request({
                url: '/user/phone',
                method: 'POST',
                data: {
                    code: code,
                    openid: this.data.openid
                }
            }).then(res => {
                wx.hideLoading()
                this.setData({
                    phone: res.phone
                }, () => {
                    this.checkCanSubmit()
                })

                wx.showToast({
                    title: '手机号已获取',
                    icon: 'success',
                    duration: 1500
                })

            }).catch(err => {
                wx.hideLoading()
                console.error('获取手机号失败', err)
                wx.showModal({
                    title: '获取手机号失败',
                    content: '请重试或联系管理员',
                    showCancel: false
                })
            })
        } else {
            // 用户拒绝授权
            wx.showModal({
                title: '需要授权',
                content: '手机号用于接收报修通知，是必填项',
                showCancel: false
            })
        }
    },

    // 提交注册
    async submitRegister() {
        const { openid, nickname, phone } = this.data

        // 验证必填项
        if (!nickname || !nickname.trim()) {
            wx.showToast({
                title: '请输入姓名',
                icon: 'none'
            })
            return
        }

        if (!phone) {
            wx.showToast({
                title: '请先获取手机号',
                icon: 'none'
            })
            return
        }

        // 防止重复提交
        if (this.data.submitting) {
            return
        }

        this.setData({ submitting: true })
        wx.showLoading({ title: '注册中...' })

        try {
            // 使用默认头像
            const avatar = '/images/default-avatar.png'

            await api.request({
                url: '/user/register',
                method: 'POST',
                data: {
                    openid,
                    nickname: nickname.trim(),
                    avatar: avatar,
                    phone
                }
            })

            // 保存用户信息到全局
            app.globalData.userInfo = {
                nickName: nickname.trim(),
                avatarUrl: avatar
            }
            app.globalData.isLoggedIn = true

            wx.hideLoading()

            wx.showToast({
                title: '注册成功',
                icon: 'success',
                duration: 2000
            })

            // 延迟跳转到首页
            setTimeout(() => {
                wx.switchTab({
                    url: '/pages/index/index'
                })
            }, 2000)

        } catch (error) {
            wx.hideLoading()
            console.error('注册失败', error)

            this.setData({ submitting: false })

            wx.showModal({
                title: '注册失败',
                content: error.message || '请稍后重试',
                showCancel: false
            })
        }
    }
})
